import * as THREE from 'three';
import { Vec3 } from '@/core/types';
import { PassiveEntity } from './PassiveEntity';
import { EntityType, EntityStats } from './types';
import { WorldManager } from '@/world/WorldManager';
import { ItemDropManager } from '@/world/ItemDrop';
import { BlockType } from '@/blocks/types';
import { getAudioManager } from '@/audio/AudioManager';

export class Sheep extends PassiveEntity {
  private woolColor: number;
  private hasWool: boolean;

  constructor(id: string, position: Vec3, worldManager: WorldManager, itemDropManager?: ItemDropManager) {
    const stats: EntityStats = {
      maxHealth: 8,
      moveSpeed: 1.3,
      jumpHeight: 1.2,
      detectionRange: 7,
      size: { width: 1.3, height: 1.3 }
    };

    super(id, EntityType.SHEEP, position, worldManager, stats, itemDropManager);
    
    // 随机羊毛颜色
    const colors = [0xFFFFFF, 0x808080, 0x000000, 0x8B4513, 0xFFC0CB];
    this.woolColor = colors[Math.floor(Math.random() * colors.length)];
    this.hasWool = true;
  }

  protected createMesh(): void {
    // 创建一个简单的羊模型
    const group = new THREE.Group();

    // 身体（羊毛）
    if (this.hasWool) {
      const woolGeometry = new THREE.BoxGeometry(1.3, 0.8, 0.9);
      const woolMaterial = new THREE.MeshLambertMaterial({ color: this.woolColor });
      const wool = new THREE.Mesh(woolGeometry, woolMaterial);
      wool.position.set(0, 0.4, 0);
      group.add(wool);
    } else {
      // 剪毛后的身体
      const bodyGeometry = new THREE.BoxGeometry(1.0, 0.6, 0.7);
      const bodyMaterial = new THREE.MeshLambertMaterial({ color: 0xFFB6C1 }); // 粉色皮肤
      const body = new THREE.Mesh(bodyGeometry, bodyMaterial);
      body.position.set(0, 0.3, 0);
      group.add(body);
    }

    // 头部
    const headGeometry = new THREE.BoxGeometry(0.4, 0.4, 0.5);
    const headMaterial = new THREE.MeshLambertMaterial({ color: 0xF5F5F5 }); // 浅灰色
    const head = new THREE.Mesh(headGeometry, headMaterial);
    head.position.set(0, 0.6, -0.6);
    group.add(head);

    // 腿部
    const legGeometry = new THREE.BoxGeometry(0.15, 0.5, 0.15);
    const legMaterial = new THREE.MeshLambertMaterial({ color: 0x000000 }); // 黑色腿
    
    const positions = [
      [-0.4, -0.25, -0.3], // 前左腿
      [0.4, -0.25, -0.3],  // 前右腿
      [-0.4, -0.25, 0.3],  // 后左腿
      [0.4, -0.25, 0.3]    // 后右腿
    ];

    positions.forEach(pos => {
      const leg = new THREE.Mesh(legGeometry, legMaterial);
      leg.position.set(pos[0], pos[1], pos[2]);
      group.add(leg);
    });

    // 耳朵
    const earGeometry = new THREE.BoxGeometry(0.1, 0.15, 0.05);
    const earMaterial = new THREE.MeshLambertMaterial({ color: 0xFFB6C1 });
    
    const leftEar = new THREE.Mesh(earGeometry, earMaterial);
    leftEar.position.set(-0.15, 0.7, -0.7);
    leftEar.rotation.z = -Math.PI / 4;
    group.add(leftEar);
    
    const rightEar = new THREE.Mesh(earGeometry, earMaterial);
    rightEar.position.set(0.15, 0.7, -0.7);
    rightEar.rotation.z = Math.PI / 4;
    group.add(rightEar);

    // 如果有羊毛，添加一些蓬松效果
    if (this.hasWool) {
      const fluffGeometry = new THREE.SphereGeometry(0.1, 6, 6);
      const fluffMaterial = new THREE.MeshLambertMaterial({ color: this.woolColor });
      
      for (let i = 0; i < 8; i++) {
        const fluff = new THREE.Mesh(fluffGeometry, fluffMaterial);
        fluff.position.set(
          (Math.random() - 0.5) * 1.2,
          0.2 + Math.random() * 0.4,
          (Math.random() - 0.5) * 0.8
        );
        group.add(fluff);
      }
    }

    // 设置阴影
    group.traverse((child) => {
      if (child instanceof THREE.Mesh) {
        child.castShadow = true;
        child.receiveShadow = true;
      }
    });

    this.mesh = group;
  }

  protected dropItems(): void {
    // 羊死亡时掉落羊毛和羊肉
    console.log(`Sheep ${this.id} dropped wool and mutton`);
    
    if (this.itemDropManager) {
      // 如果有羊毛，掉落羊毛 (1-3个)
      if (this.hasWool) {
        const woolCount = 1 + Math.floor(Math.random() * 3);
        this.itemDropManager.dropItem(BlockType.WOOL, woolCount, this.position);
      }
      // 掉落羊肉 (1-2个)
      const muttonCount = 1 + Math.floor(Math.random() * 2);
      this.itemDropManager.dropItem(BlockType.MUTTON, muttonCount, this.position);
    }
  }

  public update(deltaTime: number): void {
    super.update(deltaTime);
    
    // 添加羊特有的行为
    this.addSheepBehavior(deltaTime);
  }

  private addSheepBehavior(deltaTime: number): void {
    // 偶尔发出羊叫声
    if (Math.random() < 0.0005) {
      console.log(`Sheep ${this.id}: Baa!`);
      this.playIdleSound();
    }

    // 羊毛重新生长（简化版）
    if (!this.hasWool && Math.random() < 0.0001) { // 很低的概率重新长毛
      this.regrowWool();
    }

    // 头部轻微摆动
    if (this.mesh) {
      const head = this.mesh.children[1]; // 头部
      if (head) {
        head.rotation.x = Math.sin(this.age * 1.5) * 0.05;
      }
    }
  }

  private playIdleSound(): void {
    const audioManager = getAudioManager();
    audioManager.playSound('sheep_idle', {
      position: this.position,
      volume: 0.5
    });
  }

  // 剪羊毛
  public shearWool(): boolean {
    if (this.hasWool) {
      this.hasWool = false;
      this.recreateMesh();
      console.log(`Sheep ${this.id} was sheared!`);
      return true;
    }
    return false;
  }

  // 羊毛重新生长
  private regrowWool(): void {
    if (!this.hasWool) {
      this.hasWool = true;
      this.recreateMesh();
      console.log(`Sheep ${this.id} regrew its wool!`);
    }
  }

  private recreateMesh(): void {
    // 移除旧网格
    if (this.mesh && this.mesh.parent) {
      this.mesh.parent.remove(this.mesh);
    }
    
    // 创建新网格
    this.createMesh();
  }

  // 羊可以被小麦吸引
  public canBeAttractedBy(item: string): boolean {
    return item === 'wheat';
  }

  public getWoolColor(): number {
    return this.woolColor;
  }

  public hasWoolCoat(): boolean {
    return this.hasWool;
  }
}